package com.fu.servlet;

import com.fu.bean.Student;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * @author 付大大
 * @description
 * @create 2021-01-24 11:35
 */
@WebServlet("/servletDemo05")
public class ServletDemo05 extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Map<String, String[]> parameterMap = req.getParameterMap();

        Student student = new Student();



        for (String key : parameterMap.keySet()) {
            String[] value = parameterMap.get(key);

            try {
                /*获取Student对象的属性描述器*/
                PropertyDescriptor descriptor = new PropertyDescriptor(key, student.getClass());
                /*获取对应的setXxx方法*/
                Method writeMethod = descriptor.getWriteMethod();
                /*执行对应的方法*/
                if (value.length > 1) {
                    writeMethod.invoke(student, (Object) value);
                } else {
                    writeMethod.invoke(student, value);
                }

            } catch (IntrospectionException | IllegalAccessException | InvocationTargetException e) {
                e.printStackTrace();
            }
        }

        System.out.println(student);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
